package com.czk.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.czk.common.utils.R;
import com.czk.common.vo.MemberResponseVo;
import com.czk.gulimall.auth.feign.MemberFeignService;
import com.czk.gulimall.auth.utils.HttpClientUtils;
import com.czk.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/3/1 21:54
 */
@Controller
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping(value = "/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {

        Map<String, String> map = new HashMap<>();
        map.put("client_id", "2077705774");
        map.put("client_secret", "40af02bd1c7e435ba6a6e9cd3bf799fd");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);

        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpClientUtils.postForm_1("https://api.weibo.com/oauth2/access_token", map, null, HttpClientUtils.connTimeout, HttpClientUtils.readTimeout);
        if (response.getStatusLine().getStatusCode() == 200) {
            // 正常
            String string = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(string, SocialUser.class);
            R login = memberFeignService.login(socialUser);
            if (login.getCode() == 0) {
                JSONObject data = (JSONObject) login.getData("data", new TypeReference<Object>() {
                });
                MemberResponseVo memberResponseVo = JSON.toJavaObject(data, MemberResponseVo.class);
                // 第一次使用session，命令浏览器保存卡号 jessionid
                // 以后访问哪个网站就会带上该网站的cookie
                // 子域之间，guliamll.com、auth.gulimall.com、order.gulimall.com不能互相使用
                // 添加session的时候，指定作用域名为父域名
                // todo 1 作用域是当前域，不能解决子域session共享问题
                // todo 2  以json的方式存放数据，而不是jdk
                session.setAttribute("loginUser", memberResponseVo);
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
